<template>
  <div class="vip-card-bag app-main-content-box">
    <app-main-title title="同步微信卡包" />
    <div v-if="!showNoAuth">
      <!-- 说明 -->
      <div class="app-main-tips-box">
        <div class="title">
          <i class="el-icon-warning" /> 同步说明
        </div>
        <ul>
          <!-- <li>1.首次同步到微信需要在微信创建会员卡，此流程需要等待微信官方的审核，审核时间预估三个工作日，当前审核状态：未提交。</li> -->
          <li>1.首次同步到微信需要在微信创建会员卡，此流程需要等待微信官方的审核，审核时间预估三个工作日。</li>
          <li>2.首次同步成功后，后续的更新和同步都可立即生效。</li>
        </ul>
      </div>
      <div class="content">
        <!-- 左边展示 -->
        <div class="left">
          <div class="card">
            <div :style="{backgroundColor:activeThemeColor}" class="card-bg">
              <!-- <img :src="imageUrl" alt> -->
            </div>
            <div class="card-logo">
              <img
                v-if="userInfo.business.logoUrl"
                :src="fileBaseUrl+userInfo.business.logoUrl"
                alt
              >
            </div>
            <div class="card-qr-code">
              <svg-icon icon-class="s-i-qrcode" class="qr-code" />
            </div>
            <span class="card-name">{{ userInfo.business.name?userInfo.business.name:"简称" }}</span>
            <span class="card-type">微信会员卡</span>
            <span class="card-number">1234 5678 9888</span>
          </div>

          <!-- 栏位 -->
          <el-row v-if="form.customFields.length!=0" type="flex" class="gird">
            <el-col v-if="form.customFields.indexOf('CUSTOM_FIELD_POINT')!=-1" :span="24">
              <div class="gird-title">积分</div>
              <div :style="{color:activeThemeColor}" class="gird-content">8888</div>
            </el-col>
            <el-col v-if="form.customFields.indexOf('CUSTOM_FIELD_CARD_TYPE')!=-1" :span="24">
              <div class="gird-title">卡类型</div>
              <div :style="{color:activeThemeColor}" class="gird-content">超级会员</div>
            </el-col>
            <el-col v-if="form.customFields.indexOf('CUSTOM_FIELD_BALANCE')!=-1" :span="24">
              <div class="gird-title">我的账户</div>
              <div :style="{color:activeThemeColor}" class="gird-content">查看</div>
            </el-col>
            <el-col v-if="form.customFields.indexOf('CUSTOM_FIELD_COUPON')!=-1" :span="24">
              <div class="gird-title">优惠券</div>
              <div :style="{color:activeThemeColor}" class="gird-content">查看</div>
            </el-col>
          </el-row>
          <!-- 会员中心 -->
          <div class="vip-center">
            <div
              :style="{color:activeThemeColor, border:'1px solid '+activeThemeColor}"
              class="btn"
            >会员中心</div>
          </div>
          <!-- 功能列表 -->
          <ul class="card-menu">
            <li v-for="(item,index) in form.customCells" :key="index">
              <div>{{ item.title }}</div>
              <div>{{ item.subTitle }}</div>
            </li>
            <li>
              <div>会员卡详情</div>
              <div />
            </li>
            <li>
              <div>公众号</div>
              <div />
            </li>
          </ul>
        </div>

        <!-- 右边表单 -->
        <div v-loading="loading" class="right" element-loading-text="同步中">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
            <el-form-item label="主题颜色：" prop="color">
              <ul class="card-theme-color">
                <li
                  v-for="(item,index) in themeColor"
                  :key="index"
                  :style="{backgroundColor:item.color}"
                  @click="setTheme(item)"
                >
                  <svg-icon
                    v-if="form.color == item.name"
                    icon-class="s-i-tick-plain"
                    class="right-svg"
                  />
                </li>
              </ul>
            </el-form-item>

            <!-- 卡面 -->
            <el-form-item label="卡面：" prop="levelBackground">
              <el-radio-group v-model="form.levelBackground" style="line-height:32px;">
                <el-radio :label="1">根据会员卡类型自动设置卡面</el-radio>
                <br>
                <el-radio :label="0">所有会员统一卡面</el-radio>
              </el-radio-group>
              <el-collapse-transition>
                <div v-if="form.levelBackground === 0">
                  <div class="clearfix">
                    <el-upload
                      :action="actionUrl"
                      :show-file-list="false"
                      :headers="uploadHeaders"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                      class="fl app-uploader-img-plus"
                    >
                      <img
                        v-if="form.backgroundPicPath"
                        :src="fileBaseUrl+form.backgroundPicPath"
                        class="avatar"
                      >
                      <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
                    </el-upload>
                    <ul class="fl upload-tips">
                      <li>图片要求：</li>
                      <li>1.上传的图片大小不超过1MB，仅支持JPG/PNG格式</li>
                      <li>2.像素大小控制在1000像素*600像素以下</li>
                      <li>
                        <el-button size="small" @click="openCardImgMap ">从系统图库中选择</el-button>
                      </li>
                    </ul>
                  </div>
                </div>
              </el-collapse-transition>
            </el-form-item>

            <!-- 栏位显示 -->
            <el-form-item label="自定义栏位：" prop="customFields">
              <el-checkbox-group v-model="form.customFields">
                <el-checkbox label="CUSTOM_FIELD_POINT">积分</el-checkbox>
                <el-checkbox label="CUSTOM_FIELD_CARD_TYPE">卡类型</el-checkbox>
                <el-checkbox label="CUSTOM_FIELD_BALANCE">我的账户</el-checkbox>
                <el-checkbox label="CUSTOM_FIELD_COUPON">优惠券</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <!-- 自定义入口 -->
            <el-form-item label="栏位显示：" prop="customCells">
              <el-checkbox-group v-model="customCellsTitle" @change="customCellsChange">
                <el-checkbox
                  v-for="(item,index) in customCellsOptions"
                  :key="index"
                  :label="item.title"
                />
              </el-checkbox-group>
            </el-form-item>

            <!-- <el-form-item label="自定义入口：">
            <el-card class="menu-box">
              <div class="clearfix">
                <el-button type="text" @click.prevent="removeMenuList()" class="fr">删除</el-button>
              </div>
              <el-form-item label="名称：">
                <el-input placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item label="提示语：">
                <el-input placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item label="跳转：">
                <el-radio-group>
                  <el-radio :label="3">推荐跳转</el-radio>
                  <el-radio :label="6">自定义跳转</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-card>
            <el-button type="text" icon="el-icon-plus" @click="addMenuList">增加自定义入口</el-button>
            </el-form-item>-->
            <el-form-item label="一键激活字段：">
              <el-button size="small" @click="openDialogFields">设置字段</el-button>
              &nbsp;&nbsp;当前字段：{{ optionalText }}
            </el-form-item>

            <el-form-item>
              <el-button type="primary" round @click="onSubmitForm">同步到微信</el-button>
              <div v-if="statusInfo" class="app-text-color-dark" style="display:inline-block">
                &nbsp;&nbsp;最近一次同步时间为{{ statusInfo.updateTime }}
                <span v-if="statusInfo.cardId">（卡id：{{ statusInfo.cardId }}  <el-button
                  v-clipboard:copy="statusInfo.cardId"
                  v-clipboard:success="onCopy"
                  type="text"
                >复制</el-button>），</span>
                <span
                  :class="statusOptions[statusInfo.status].class"
                >{{ statusOptions[statusInfo.status].value }}</span>
                <span
                  v-if="statusInfo.status==='CARD_STATUS_VERIFY_FAIL'&&statusInfo.reason"
                  class="app-text-color-danger"
                >，{{ statusInfo.reason }}</span>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 图库 -->
    <card-img-map ref="cardImgMap" img-type="卡面" />

    <!-- 弹框顾客需要填写的字段 -->
    <dialog-fields
      ref="dialogFields"
      :fields="fields"
      :required-form.sync="requiredForm"
      :optional-form.sync="optionalForm"
    />

    <!-- 未授权公众号 -->
    <wx-auth-tips v-if="showNoAuth" source="public" />
  </div>
</template>

<script>
import { imgUploadUrl } from '@/api/upload'
import { mapGetters, mapActions } from 'vuex'
import DialogFields from './components/DialogFields.vue'
import { getConfig, saveConfig, getConfigStatus } from '@/api/wxCard'
import { getToken } from '@/utils/auth'
export default {
  components: {
    DialogFields
  },
  data() {
    /**
       * 表单校验方法相关
       */
    const validateCustomFields = (rule, value, callback) => {
      if (value === []) {
        callback()
      } else if (value.length >= 4) {
        callback(new Error('最多只能选择三种栏位'))
      } else {
        callback()
      }
    }
    const validateCustomCells = (rule, value, callback) => {
      if (value === []) {
        callback()
      } else if (this.customCellsTitle.length >= 5) {
        callback(new Error('最多只能选择四种自定义入口'))
      } else {
        callback()
      }
    }
    const validateLevelBackground = (rule, value, callback) => {
      if (value === 1) {
        this.$refs.form.clearValidate(['levelBackground'])
        callback()
      } else if (this.form.backgroundPicPath) {
        callback()
      } else {
        callback(new Error('请上传或从图库选择卡面'))
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        color: [
          {
            required: true,
            message: '请选择主题色',
            trigger: ['blur', 'change']
          }
        ],
        customFields: [
          {
            validator: validateCustomFields,
            trigger: ['change']
          }
        ],
        customCells: [
          {
            validator: validateCustomCells,
            trigger: ['change']
          }
        ],
        levelBackground: [
          {
            required: true,
            validator: validateLevelBackground,
            trigger: ['change']
          }
        ]
      },
      // 配置
      customCellsOptions: [
        {
          appBrandPass: 'pages/bookingProductModule/pages/bookingIndex/main',
          subTitle: '会员特惠价',
          title: '在线订房',
          url: ''
        },
        {
          appBrandPass: 'pages/myIntegral/main',
          subTitle: '兑换好礼',
          title: '积分商城',
          url: ''
        },
        {
          appBrandPass: 'pages/index/main',
          subTitle: '更多优惠',
          title: '会员中心',
          url: ''
        },

        {
          appBrandPass: 'pages/balance/main',
          subTitle: '充值有礼',
          title: '会员卡充值',
          url: ''
        },
        {
          appBrandPass: 'pages/sendCardBuy/main',
          subTitle: '表达你的心意',
          title: '赠送好友VIP',
          url: ''
        },
        {
          appBrandPass: 'pages/inviteRegister/main',
          subTitle: '邀请得好礼',
          title: '邀请好友',
          url: ''
        }
      ],
      statusOptions: {
        CARD_STATUS_NOT_VERIFY: {
          value: '同步中',
          class: 'app-text-color-primary'
        },
        CARD_STATUS_VERIFY_FAIL: {
          value: '同步失败',
          class: 'app-text-color-danger'
        },
        CARD_STATUS_DELETE: {
          value: '卡券被商户删除',
          class: 'app-text-color-danger'
        },
        CARD_STATUS_VERIFY_OK: {
          value: '同步成功',
          class: 'app-text-color-success'
        }
      },
      // 状态
      loading: false,
      showNoAuth: false, // 是否授权
      // 数据
      // imageUrl: "",
      actionUrl: imgUploadUrl, // 上传地址
      uploadHeaders: {}, // 上传请求头
      fields: [], // 勾选字段
      requiredForm: [1, 2], // 原始必填
      optionalForm: [], // 原始选填
      optionalText: '姓名、手机号', // 已经选择
      themeColor: [], // 主题列表
      activeThemeColor: '#606266', // 当前激活主题颜色
      customCellsTitle: [], // customCells勾选临时值
      statusInfo: '',
      form: {
        color: '',
        backgroundPicPath: '',
        levelBackground: 1,
        customFields: [],
        customCells: [],
        requiredForm: [1, 2],
        optionalForm: []
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'userInfo'])
  },
  mounted() {
    // 页面初始化
    this.checkAuth()
  },
  methods: {
    /**
       *  获取数据
       */
    ...mapActions(['getAuthMp']),
    // 检验是否授权了
    checkAuth() {
      this.getAuthMp().then(() => {
        this.$store.state.wechat.mpInfo.default.appId
          ? this.initData()
          : (this.showNoAuth = true)
      })
    },

    initData() {
      this.fetchData()
      this.initStatus()
    },

    // 获取状态
    initStatus() {
      getConfigStatus()
        .then(res => {
          this.statusInfo = res.data
        })
        .catch(err => {})
        .finally(() => {})
    },

    // 获取配置
    fetchData() {
      return getConfig().then(res => {
        this.themeColor = res.data.formConfig.colors
        this.fields = res.data.formConfig.fields
        if (res.data.form) {
          this.form = res.data.form
          // 获取颜色值
          this.themeColor.forEach(val => {
            if (this.form.color === val.name) {
              this.activeThemeColor = val.color
            }
          })
          // 栏位
          if (res.data.form.customFields) {
            this.form.customFields = res.data.form.customFields.split(',')
          } else {
            this.form.customFields = []
          }

          // 自定义入口
          if (res.data.form.customCells) {
            const customCellsParse = JSON.parse(res.data.form.customCells)
            this.form.customCells = customCellsParse
            customCellsParse.forEach(v => {
              this.customCellsTitle.push(v.title)
            })
          } else {
            this.form.customCells = []
          }
          // 激活字段
          if (res.data.form.optionalForm) {
            this.optionalForm = res.data.form.optionalForm
              .split(',')
              .map(Number)
          } else {
            this.optionalForm = []
          }
          if (res.data.form.requiredForm) {
            this.requiredForm = res.data.form.requiredForm
              .split(',')
              .map(Number)
          } else {
            this.requiredForm = [1, 2]
          }
        }
        this.setOptionalText()
      })
    },

    /**
       *  按钮组
       */
    // 同步到微信卡包
    onSubmitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = Object.assign({}, this.form)
          params.customFields = params.customFields.join(',')
          params.customCells =
              params.customCells.length === 0
                ? ''
                : JSON.stringify(params.customCells)
          params['requiredForm'] = this.requiredForm.join(',')
          params['optionalForm'] = this.optionalForm.join(',')
          this.loading = true
          saveConfig(params)
            .then(res => {
              this.loading = false
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '同步成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
              }
              this.initStatus()
            })
            .catch(err => {
              this.loading = false
            })
        }
      })
    },

    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.backgroundPicPath = res.data.path
        this.$refs.form.clearValidate(['levelBackground'])
      } else {
        this.$message.error(res.msg)
      }
    },

    // 上传前处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 1000, 600, 1)
    },

    // 选择主题色
    setTheme(item) {
      this.form.color = item.name
      this.activeThemeColor = item.color
    },

    // 打开填写字段弹框
    openDialogFields() {
      this.$refs.dialogFields.open().then(res => {
        this.requiredForm = res.requiredForm
        this.optionalForm = res.optionalForm
        this.setOptionalText()
      })
    },

    // 增加自定义菜单
    // addMenuList() {},

    // 删除自定义菜单
    removeMenuList() {},

    // 打开图库
    openCardImgMap() {
      this.$refs.cardImgMap.open().then(res => {
        this.form.backgroundPicPath = res
        this.$refs.form.clearValidate(['levelBackground'])
      })
    },

    // 复制
    onCopy() {
      this.$message.success('已复制链接到剪切板')
    },

    /**
       * 状态
       */
    // 自定义入口变更
    customCellsChange(val) {
      const params = []
      this.customCellsOptions.forEach(v => {
        if (this.customCellsTitle.includes(v.title)) {
          params.push(v)
        }
      })
      this.form.customCells = params
    },

    /**
       *  方法
       */
    // 获取当前选择字段文本
    setOptionalText() {
      const strArray = []
      this.fields.forEach((item, index) => {
        const allOption = this.optionalForm.concat(this.requiredForm)
        if (allOption.indexOf(item.id) !== -1) {
          strArray.push(item.fieldName)
        }
        this.optionalText = strArray.join('、')
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .content {
    margin-top: 10px;
  }
  .left {
    float: left;
    position: relative;
    box-sizing: border-box;
    width: 290px;
    height: 600px;
    margin-right: 20px;
    background: url("../../../assets/img/iphone_bg.png") no-repeat;
    background-size: 100% auto;
    padding: 80px 25px 80px;
    /* 卡面 */
    .card {
      position: relative;
      width: 230px;
      margin-left: 5px;
      height: 130px;
      border-radius: 5px;
      color: #fff;
      &-bg {
        width: 100%;
        height: 100%;
        border-radius: 6px;
      }
      &-logo {
        overflow: hidden;
        position: absolute;
        top: 12px;
        left: 16px;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border: 1px solid #e7e7e7;
      }
      &-qr-code {
        position: absolute;
        top: 20px;
        right: 20px;
        width: 20px;
        height: 20px;
        border-radius: 2px;
        background-color: #fff;
        .qr-code {
          width: 100%;
          height: 100%;
        }
      }
      &-name {
        position: absolute;
        top: 12px;
        left: 60px;
        font-size: 14px;
      }
      &-type {
        position: absolute;
        top: 36px;
        left: 60px;
        font-size: 12px;
      }
      &-number {
        position: absolute;
        bottom: 10px;
        left: 10px;
        font-size: 14px;
      }
    }
    /* 卡方格 */
    .gird {
      margin-top: 10px;
      font-size: 13px;
      .el-col {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 50px;
      }
      .el-col:not(:last-child) {
        border-right: 1px solid #e7e7e7;
      }
      &-title {
        margin-bottom: 10px;
        font-size: 12px;
      }
    }

    /* 会员中心 */
    .vip-center {
      margin-top: 10px;
      .btn {
        margin: 0 auto;
        width: 110px;
        height: 30px;
        border: 1px solid #eee;
        border-radius: 6px;
        line-height: 30px;
        font-size: 14px;
        text-align: center;
      }
    }

    /* 卡功能 */
    .card-menu {
      margin-top: 10px;
      li {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 28px;
        padding: 0 6px;
        line-height: 28px;
        border-bottom: 1px solid #e6e6e6;
        font-size: 14px;
        div:last-child {
          color: $light-font-color;
        }
      }
    }
  }
  .right {
    overflow: hidden;
    box-sizing: border-box;
    min-width: 300px;
    min-height: 700px;
    padding-top: 20px;
    -webkit-box-sizing: border-box;
    border-radius: 10px;
    /* 卡主题色 */
    .card-theme-color {
      li {
        float: left;
        position: relative;
        width: 30px;
        height: 30px;
        margin: 5px 10px 5px 0;
        border-radius: 50%;
        .right-svg {
          position: absolute;
          top: -12px;
          left: 9px;
          font-size: 14px;
        }
      }
    }
    /* 上传 */
    .app-uploader-img-plus {
      width: 300px;
      height: 180px;
    }
    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 300px;
      height: 180px;
      line-height: 170px;
      text-align: center;
    }
    .avatar {
      width: 300px;
      height: 180px;
      display: block;
    }
    .upload-tips {
      margin: 20px 0 0 20px;
      li {
        margin-top: 10px;
        font-size: 14px;
        line-height: 16px;
        color: $dark-font-color;
      }
    }
    // 覆盖checkbox
    .el-checkbox + .el-checkbox {
      margin-left: 0;
    }
    .el-checkbox {
      margin-right: 30px;
    }
  }
</style>
